﻿using Fiddler;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace FiddlerCore
{
    //http://www.cnblogs.com/myprogram/p/5042562.html
    public class Class1
    {
        public void test()
        {
            ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
            FiddlerApplication.Startup(9898, FiddlerCoreStartupFlags.Default);
            Fiddler.FiddlerApplication.OnNotification += FiddlerApplication_OnNotification;
            Fiddler.FiddlerApplication.Log.OnLogString += Log_OnLogString;
            Fiddler.FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
            Fiddler.FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
            Fiddler.FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
            Fiddler.CONFIG.IgnoreServerCertErrors = false;
            CONFIG.bCaptureCONNECT = true;
            //   FiddlerApplication.Prefs.SetStringPref("fiddler.config.path.makecert", @"c:\Program Files (x86)\Fiddler2\Makecert.exe");
            if (!CertMaker.rootCertExists())
            {
                if (!CertMaker.createRootCert())
                {
                    throw new Exception("Unable to create cert for FiddlerCore.");
                }
                X509Store certStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                certStore.Open(OpenFlags.ReadWrite);
                try
                {
                    certStore.Add(CertMaker.GetRootCertificate());
                }
                finally
                {
                    certStore.Close();
                }
            }
        }
        public void down()
        {
            FiddlerApplication.Shutdown();
        }
        void FiddlerApplication_AfterSessionComplete(Fiddler.Session sess)
        {
            // Ignore HTTPS connect requests
            if (sess.RequestMethod == "CONNECT")
            {
                return;
            }

            if (sess == null || sess.oRequest == null || sess.oRequest.headers == null)
            {
                return;
            }
            // Request
            string headers = sess.oRequest.headers.ToString();
            var reqBody = sess.GetRequestBodyAsString();

            // Response
            var resHeaders = sess.oResponse.headers.ToString();
            var resBody = sess.GetResponseBodyAsString();

            // if you wanted to capture the response
            //string respHeaders = session.oResponse.headers.ToString();
            //var respBody = session.GetResponseBodyAsString();

            // replace the HTTP line to inject full URL
            string firstLine = sess.RequestMethod + " " + sess.fullUrl + " " + sess.oRequest.headers.HTTPVersion;
            int at = headers.IndexOf("\r\n");
            if (at < 0)
                return;
            headers = firstLine + "\r\n" + headers.Substring(at + 1);

            string output = headers + "\r\n" +
                            (!string.IsNullOrEmpty(reqBody) ? reqBody + "\r\n" : string.Empty) + "\r\n\r\n";


            Console.WriteLine("Finished session:t" + sess.fullUrl);
        }

        void FiddlerApplication_BeforeResponse(Fiddler.Session oSession)
        {//   cookies = oSession.RequestHeaders["Cookie"];http://www.cnblogs.com/muxueyuan/p/6229706.html
            var cookies = oSession.RequestHeaders["Cookie"];
            if (!string.IsNullOrEmpty(cookies))
            {
                Console.WriteLine("cookie   " + cookies);
            }
            if (oSession.ResponseHeaders["Content-Type"].Contains("text/html"))
            {
                //     在BeforeResponse事件响应函数FiddlerApplication_BeforeResponse中：//http://www.cnblogs.com/liaohuolin/p/4985481.html
                string strResponse = oSession.GetResponseBodyAsString();
                //   这句是获取浏览器接收数据的字符串，在处理html格式数据时，用这个方法。
                oSession.utilSetResponseBody(strResponse);
            }

            //想如何改写Response信息在这里随意发挥了
            Console.WriteLine("BeforeResponse: {0}", oSession.responseCode);
            Debug.WriteLine("{0}:HTTP {1} for {2}", oSession.id, oSession.responseCode, oSession.fullUrl);
        }

        void FiddlerApplication_BeforeRequest(Fiddler.Session oSession)
        {
            //想如何改写Request信息在这里随意发挥了
            Debug.WriteLine("Before request for:t" + oSession.fullUrl);
            oSession.bBufferResponse = true;
        }

        void FiddlerApplication_OnNotification(object sender, Fiddler.NotificationEventArgs e)
        {
            Debug.WriteLine("** NotifyUser: " + e.NotifyString);
        }
        void Log_OnLogString(object sender, Fiddler.LogEventArgs e)
        {
            Debug.WriteLine("** LogString: " + e.LogString);
        }
    }
}
